@{
ViewData["Title"] = "恢复印章";
}

<h2 style="margin:20px 0">恢复印章</h2>
<hr />
<div class="form-group">
	<div class="col-md-offset-1 col-md-10 ">
		<form class="form-horizontal">
			<div class="form-group">
				<label class="col-sm-2 control-label">选择恢复的UKEY</label>
				<div class="col-sm-10" style="line-height: 30px;">
					<select id="userCertID" name="ukeySelect" class="form-control"></select>
				</div>
			</div>
			<input type="hidden" id="sealBase64" />
			<div class="form-group">
				<div class="col-sm-offset-2 col-sm-10">
					<input id="btnCreate" type="button" value="恢复印章" class="btn btn-default" />
				</div>
			</div>
		</form>
		<dl id="infoDiv" class="dl-horizontal" style="display: none"></dl>
	</div>
</div>

<input type="hidden" id="yz" value="" />
<div id="layerPagePinCode" style="display: none">
	<div style="padding: 50px; line-height: 22px; background-color: #393D49; color: #fff; font-weight: 300;">
		请输入用户PIN码：<br />
		<input type="password" name="ukeyPinCode" class="form-control" id="pinCode" />
		<span id="pinError"></span>
	</div>

</div>
@section scripts {
<script src="/Content/layui/layui.js" charset="utf-8"></script>
<script src="~/js/dateformat.js"></script>
<script>
	function EnumKey(funcBack, errorCallBack) {
		var socket = new WebSocket("ws://127.0.0.1:2012/CertInfo");
		try {
			socket.onerror = errorCallBack;
			socket.onopen = function(msg) {

				//alert("连接成功！");
				socket.send("abc");
			};
			socket.onmessage = function(e) {
				if (isNumber(e.data)) {
					funcBack("");
				} else {
					//alert(e.data);
					funcBack(e.data);
				}
			};
		} catch (ex) {
			funcBack("");
		}
	}

	function GetCertAndSeal(certSN, funcBack) {
		//alert(certSN);
		var dtd = $.Deferred();
		var socket = new WebSocket("ws://127.0.0.1:2012/SealAndCertBase64");
		try {
			socket.onopen = function(msg) {
				//alert("连接成功！");
				socket.send(certSN);
			};
			socket.onmessage = function(e) {
				funcBack(e.data);
				socket.close();
				dtd.resolve();
			};
		} catch (ex) {
			funcBack("");
			socket.close();
		} finally {
			return dtd.promise();
		}
	}

	function initlist(str) {
		$("select[name='ukeySelect']").each(function(index, element) {
			if (str == "") {
				$(element).empty();
			}
			var certList = $.parseJSON(str);
			var selObj = $(element);
			var maxIndex = $(element).find("option:last").index(); //获取Select最大的索引值
			//alert(maxIndex);
			for (var i = maxIndex; i >= 0; i--) {
				//alert(i);
				var exsitFlag = false;
				var currentValue = $(element).find("option:eq(" + i + ")").val();
				for (var j = 0; j < certList.CertInfolist.length; j++) {
					if (currentValue == certList.CertInfolist[j].CertID) {
						exsitFlag = true;
						break;
					}
				}
				if (exsitFlag == false) {
					$(element).find("option:eq(" + i + ")").remove();
				}
			}
			for (var i = 0; i < certList.CertInfolist.length; i++) {
				if ($(element).find("option[value='" + certList.CertInfolist[i].CertID + "']").index() == -1) {
					selObj.append("<option value='" + certList.CertInfolist[i].CertID + "'>" + certList.CertInfolist[i].CertCN +
						"</option>");
				}
			}

		});
	}

	function myPost(url, args) {
		var body = $(document.body),
			form = $("<form method='post'></form>"),
			input;
		form.attr({
			"action": url
		});
		$.each(args, function(key, value) {
			input = $("<input type='hidden'>");
			input.attr({
				"name": key
			});
			input.val(value);
			form.append(input);
		});

		form.appendTo(document.body);
		form.submit();
		document.body.removeChild(form[0]);
	}

	function isNumber(val) {

		var regPos = /^\d+(\.\d+)?$/; //非负浮点数
		var regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数
		if (regPos.test(val) || regNeg.test(val)) {
			return true;
		} else {
			return false;
		}
	}

	function DisplayMessage(message) {
		var mydate = new Date();
		$("#infoDiv").append("<dt>" +
			mydate.Format("hh:mm:ss") +
			"</dt><dd>" +
			message +
			"</dd>");
	}


	//写入印章数据
    function WriteUkey(base64) {
        console.log(base64)
		var dtd = $.Deferred();
		var uri = "ws://127.0.0.1:2012/WriteUkey";
		var socket = new WebSocket(uri);
		socket.onopen = function(e) {
			console.log("connected");
			var data = {
				certID: $("#userCertID").val(),
                fileName: "_HNCA_GMSEAL_",
				dataBase64: base64
			};
			socket.send(JSON.stringify(data));
		};
		socket.onclose = function(e) {
			console.log("closed");
		};
		socket.onmessage = function(e) {
			console.log(e.data);
			if (e.data == "Ok") {
				dtd.resolve(e.data);
			} else {
				DisplayMessage(e.data);
				$("#btnCreate").attr("disabled", false);
            }
			socket.close();
		};
		socket.onerror = function(e) {
			console.log("Error: " + e.data);
		};
		return dtd.promise();
	}
	//外部jie密
	function DecryptCustomizeEnvelope(Json, funcBack) {
		console.log(Json)
        var socket = new WebSocket("ws://127.0.0.1:2012/DecryptCustomizeEnvelope");
		try {

			socket.onopen = function(msg) {
				socket.send(Json);
			};
			socket.onmessage = function(e) {
				funcBack(e.data);
				socket.close();
			};
		} catch (ex) {
			funcBack("");
			socket.close();
		}

	}

	function base64toBlob(b64Data, contentType, sliceSize) {
		contentType = contentType || '';
		sliceSize = sliceSize || 512;
		var byteCharacters = atob(b64Data);
		var byteArrays = [];
		for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
			var slice = byteCharacters.slice(offset, offset + sliceSize);
			var byteNumbers = new Array(slice.length);
			for (var i = 0; i < slice.length; i++) {
				byteNumbers[i] = slice.charCodeAt(i);
			}
			var byteArray = new Uint8Array(byteNumbers);
			byteArrays.push(byteArray);
		}
		var blob = new Blob(byteArrays, {
			type: contentType
		});
		return blob;
    }
    function VerifyPin(strJson, funcBack) {

        //alert(strJson);
        var socket = new WebSocket("ws://127.0.0.1:2012/VerifyPin");
        try {

            socket.onopen = function (msg) {

                //alert("连接成功！");
                socket.send(strJson); 
            };
            socket.onmessage = function (e) {
                funcBack(e.data);
                socket.close();
            };
        } catch (ex) {
            funcBack("");
            socket.close();
        }

    }
	/*
	  通用的打开下载对话框方法，没有测试过具体兼容性
	  url 下载地址，也可以是一个blob对象，必选
	  saveName 保存文件名，可选
	*/
	function openDownloadDialog(url, saveName) {
		if (typeof url == 'object' && url instanceof Blob) {
			url = URL.createObjectURL(url); // 创建blob地址
		}
		var aLink = document.createElement('a');
		aLink.href = url;
		aLink.download = saveName || ''; // HTML5新增的属性，指定保存文件名，可以不要后缀，注意，file:///模式下不会生效
		var event;
		if (window.MouseEvent) event = new MouseEvent('click');
		else {
			event = document.createEvent('MouseEvents');
			event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
		}
		aLink.dispatchEvent(event);
	}
	//Base64编码
	function Base64() {
		// private property
		_keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

		// public method for encoding
		this.encode = function(input) {
			var output = "";
			var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
			var i = 0;
			input = _utf8_encode(input);
			while (i < input.length) {
				chr1 = input.charCodeAt(i++);
				chr2 = input.charCodeAt(i++);
				chr3 = input.charCodeAt(i++);
				enc1 = chr1 >> 2;
				enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
				enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
				enc4 = chr3 & 63;
				if (isNaN(chr2)) {
					enc3 = enc4 = 64;
				} else if (isNaN(chr3)) {
					enc4 = 64;
				}
				output = output +
					_keyStr.charAt(enc1) +
					_keyStr.charAt(enc2) +
					_keyStr.charAt(enc3) +
					_keyStr.charAt(enc4);
			}
			return output;
		};

		// public method for decoding
		this.decode = function(input) {
			var output = "";
			var chr1, chr2, chr3;
			var enc1, enc2, enc3, enc4;
			var i = 0;
			input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
			while (i < input.length) {
				enc1 = _keyStr.indexOf(input.charAt(i++));
				enc2 = _keyStr.indexOf(input.charAt(i++));
				enc3 = _keyStr.indexOf(input.charAt(i++));
				enc4 = _keyStr.indexOf(input.charAt(i++));
				chr1 = (enc1 << 2) | (enc2 >> 4);
				chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
				chr3 = ((enc3 & 3) << 6) | enc4;
				output = output + String.fromCharCode(chr1);
				if (enc3 != 64) {
					output = output + String.fromCharCode(chr2);
				}
				if (enc4 != 64) {
					output = output + String.fromCharCode(chr3);
				}
			}
			output = _utf8_decode(output);
			return output;
		};

		// private method for UTF-8 encoding
		_utf8_encode = function(string) {
			string = string.replace(/\r\n/g, "\n");
			var utftext = "";
			for (var n = 0; n < string.length; n++) {
				var c = string.charCodeAt(n);
				if (c < 128) {
					utftext += String.fromCharCode(c);
				} else if ((c > 127) && (c < 2048)) {
					utftext += String.fromCharCode((c >> 6) | 192);
					utftext += String.fromCharCode((c & 63) | 128);
				} else {
					utftext += String.fromCharCode((c >> 12) | 224);
					utftext += String.fromCharCode(((c >> 6) & 63) | 128);
					utftext += String.fromCharCode((c & 63) | 128);
				}

			}
			return utftext;
		};

		// private method for UTF-8 decoding
		_utf8_decode = function(utftext) {
			var string = "";
			var i = 0;
			var c = c1 = c2 = 0;
			while (i < utftext.length) {
				c = utftext.charCodeAt(i);
				if (c < 128) {
					string += String.fromCharCode(c);
					i++;
				} else if ((c > 191) && (c < 224)) {
					c2 = utftext.charCodeAt(i + 1);
					string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
					i += 2;
				} else {
					c2 = utftext.charCodeAt(i + 1);
					c3 = utftext.charCodeAt(i + 2);
					string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
					i += 3;
				}
			}
			return string;
		};
	}

	//外部加密
	function ExternalEncrypt(Json, funcBack) {
		console.log(Json)
		var socket = new WebSocket("ws://127.0.0.1:2012/CustomizeEnvelope");
		// var socket = new WebSocket("ws://127.0.0.1:2012/PresetCertEncrypt");
		try {

			socket.onopen = function(msg) {
				socket.send(Json);
			};
			socket.onmessage = function(e) {
				console.log(e.data, "加密");
				funcBack(e.data);
				socket.close();
			};
		} catch (ex) {
			funcBack("");
			socket.close();
		}

	}

	function EncryptCertList(back) {
		var socket = new WebSocket("ws://127.0.0.1:2012/EncryptCertList");
		try {

			socket.onopen = function(msg) {
				socket.send("1");
			};
			socket.onmessage = function(e) {
				back(e.data);
				socket.close();
			};
		} catch (ex) {
			funcBack("");
			socket.close();
		}
	}
	var layer = null;
	layui.use('layer',
		function() {
			layer = layui.layer;
		});
	$(function() {
				$.ajax({
					url: "/InfoLog/ReturnValidateCode",
					type: 'get',

					success: function(data) {
						$("#yz").val(data.validateCode);
					},
				});
				EnumKey(function(data) {
						initlist(data);
					},function() {
						layer.alert("未安装UKEY支持服务！");
					});
				$('#btnCreate').click(function() {
					layer.open({
						type: 1,
						title: false //不显示标题栏
							,
						closeBtn: true,
						area: '300px;',
						shade: 0.8,
						id: 'LAY_InputPin' //设定一个id，防止重复弹出
							,
						btn: ['确定'],
						btnAlign: 'c',
						moveType: 1 //拖拽模式，0或者1
							,
						content: $("#layerPagePinCode").html(),
                        yes: function (index, layero) {
                            var pin = layero.find("input[name='ukeyPinCode']").val();
                            VerifyPin(JSON.stringify({
                                CertID: $("#userCertID").val(),
                                Pin: layero.find("input[name='ukeyPinCode']").val()
                            }),
                                function (verifyPinRet) {
                                    if (verifyPinRet != "Ok") {
                                        layero.find("#pinError").html("Pin码错误，请重新输入");
                                        layero.find("input[name='ukeyPinCode']").val("");
                                    } else {
                                        $("input[name='ukeyPinCode']").val(layero.find("input[name='ukeyPinCode']").val());
                                        layer.close(index);
                                        //console.log(layero.find("input[name='ukeyPinCode']").val(),"476748585858")
                                        var base64 = new Base64();
                                        $("#infoDiv").empty();
                                        $("#infoDiv").fadeIn();
                                        $("#btnCreate").attr("disabled", true);
                                        DisplayMessage("正在从服务器获取印章数据");
                                        console.log($("#userCertID").val());
                                        var userCertBase64 = "";
                                        var certUserSN = $("#userCertID").val();
                                        EncryptCertList((data) => {
                                            data = JSON.parse(data);
                                            let CertID = null;
                                            //获取选中的ID值
                                            $(data.CertInfolist).each((i, value) => {
                                                if (value.CertCN == $("#userCertID option:selected").text()) {
                                                    CertID = value.CertID;
                                                    return;
                                                }
                                            })
                                            var str = JSON.stringify({
                                                // certSN: certUserSN,
                                                arrayNo: $("#userCertID").val(),
                                                ValidateCode: $("#yz").val()
                                            });
                                            var External = {
                                                CertID: CertID,
                                                //编码
                                                DataBase64: base64.encode(str),
                                            };
                                            ExternalEncrypt(JSON.stringify(External), (data) => {
                                                layer.close(index)
                                                data = JSON.parse(data);
                                                if (data.error == "Ok") {
                                                    var dataToPost = {
                                                        // ArrayNo: CertID,
                                                        EncryptData: data.contentBase64
                                                    };
                                                    var dtd1 = $.get("/ProduceSign/GetRestoreSeal",
                                                        dataToPost,
                                                        function (data) {
                                                            console.log(data, "123123123");
                                                            $("#sealBase64").val(data);
                                                        });
                                                    var dtd2 = GetCertAndSeal(certUserSN, function (certAndSeal) {
                                                        var certAndSealJObject = JSON.parse(certAndSeal);
                                                        if (certAndSealJObject.CertBase64.length != 0) {
                                                            userCertBase64 = certAndSealJObject.CertBase64;
                                                        }
                                                    });
                                                    DisplayMessage("正在恢复印章");
                                                    var dtd = $.Deferred();
                                                    $.when(dtd1, dtd2).done(function () {
                                                        EncryptCertList((data) => {
                                                            data = JSON.parse(data);
                                                            // let CertID = data.CertInfolist[0].CertID;
                                                            let CertID = null;
                                                            //获取选中的ID值
                                                            $(data.CertInfolist).each((i, value) => {
                                                                if (value.CertCN == $("#userCertID option:selected").text()) {
                                                                    CertID = value.CertID;
                                                                    return;
                                                                }
                                                            })

                                                            var str = JSON.stringify({
                                                                CertID: CertID,
                                                                DataBase64: $("#sealBase64").val(),
                                                                StrPin: pin
                                                            });
                                                            DecryptCustomizeEnvelope(str, (data) => {
                                                                data = JSON.parse(data);
                                                                WriteUkey(data.contentBase64, index).done(function () {
                                                                    dtd.resolve();
                                                                });
                                                            });
                                                        });
                                                    });
                                                    dtd.done(function () {
                                                        EncryptCertList((data) => {
                                                            data = JSON.parse(data);
                                                            let CertID = null;
                                                            //获取选中的ID值
                                                            $(data.CertInfolist).each((i, value) => {
                                                                if (value.CertCN == $("#userCertID option:selected").text()) {
                                                                    CertID = value.CertID;
                                                                    return;
                                                                }
                                                            })
                                                            var str = JSON.stringify({
                                                                arrayNo: $("#userCertID").val(),
                                                                UserCN:$("#userCertID option:selected").text()
                                                            });
                                                            var External = {
                                                                CertID: CertID,
                                                                //编码
                                                                DataBase64: base64.encode(str)
                                                            };
                                                            ExternalEncrypt(JSON.stringify(External), (data) => {
                                                                data = JSON.parse(data);
                                                                if (data.error == "Ok") {
                                                                    var data = {
                                                                        // ArrayNo: CertID,
                                                                        EncryptData: data.contentBase64
                                                                    };
                                                                    $("/ProduceSign/Restore", data);
                                                                    $("#btnCreate").attr("disabled", false);
                                                                    DisplayMessage("印章恢复完成");

                                                                    //layer.close(index)

                                                                } else {

                                                                    DisplayMessage(data.error);
                                                                }
                                                            });
                                                        })

                                                    });

                                                } else {
                                                    
                                                    DisplayMessage(data.error);
                                                }
                                            });
                                        })
                                    }
                                });
                            

						}

					});
				});
			});
</script>
}
